package logic

import (
	"context"

	"order_rpc/internal/svc"
	"order_rpc/pb/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderListByIDsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetOrderListByIDsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderListByIDsLogic {
	return &GetOrderListByIDsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetOrderListByIDsLogic) GetOrderListByIDs(in *order.IDListRequest) (*order.IDListResponse, error) {
	orders, err := l.svcCtx.OrderModel.FindListByIds(l.ctx, in.Ids)
	if err != nil {
		return nil, err
	}

	if len(orders) == 0 {
		return &order.IDListResponse{Orders: []*order.OrderInfo{}}, nil
	}

	orderIDs := make([]int64, 0)
	for _, o := range orders {
		orderIDs = append(orderIDs, o.OrderId)
	}

	goodList, err := l.svcCtx.OrderGoodsModel.FindListByOrderIDList(l.ctx, orderIDs)
	if err != nil {
		return nil, err
	}

	orderMap := make(map[int64][]*order.GoodInfo)
	for _, g := range goodList {
		good := order.GoodInfo{GoodId: g.GoodId, GoodName: g.GoodName, GoodPrice: g.GoodPrice, GoodCount: g.GoodCount}
		orderMap[g.OrderId] = append(orderMap[g.OrderId], &good)
	}

	var resp []*order.OrderInfo
	for _, o := range orders {
		resp = append(resp, &order.OrderInfo{
			UserId:      o.UserId,
			OrderId:     o.OrderId,
			OrderTotal:  o.OrderTotal,
			OrderStatus: o.OrderStatus,
			CreateTime:  o.CreateTime,
			UpdateTime:  o.UpdateTime,
			DeleteTime:  o.DeleteTime,
			Goods:       orderMap[o.OrderId],
		})
	}
	return &order.IDListResponse{Orders: resp}, nil
}
